/**
 * 
 */
package modele.util;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 * @author virgil
 *
 */
public class HibernateUtil {

	 private static final SessionFactory sessionFactory;

	 static {
	   try {
	   // Create sessiinFactory 
	   sessionFactory =
		 new Configuration().configure().buildSessionFactory();
	   } catch (HibernateException ex) {
	   throw new RuntimeException("Problème de configuration : "
	   + ex.getMessage(), ex);
	   }
	   }

	 public static final ThreadLocal session = new ThreadLocal();

	 //open a new session or use of an existing opened session
	 public static Session openSession()
			throws HibernateException {
	   Session s = (Session) session.get();
	 
	   if (s == null) {
	   s = sessionFactory.openSession();
	   session.set(s);
	   }
	   return s;
	   }

	 public static void closeSession()
			throws HibernateException {
	   Session s = (Session) session.get();
	   session.set(null);
	   if (s != null)
	   s.close();
	   }
}
